<?php
require __DIR__ . '/../bootstrap.php';

$em = require __DIR__ . '/../example/em.php';

use Service\SimManager;

//$_POST['create_sim_number'] = 77782875541;

if(!isset($_POST['create_sim_puk'])){
    $_POST['create_sim_puk']=0;
}

$sim = array('number' => $_POST['create_sim_number'], 'puk' => $_POST['create_sim_puk']);

$manager = new SimManager($em);

if (!$manager->isValidPhoneNumber($sim['number'])) {
    echo '{ "message": "Такой номер уже существует!", "type": "st-error" }';
    exit();
}

$phone_number = $sim['number'];
$url = urlencode('http://agent.smart-sim.ru/ajax/podpiska.php');
//https://service.smart-sim.ru:443/api/37282879541/updates?uname=paul&upass=kam9345t&url=http%3A%2F%2Fagent.smart-sim.ru%2Fajax%2Fpodpiska.php
function check($phone_number, $url, $manager, $sim)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://service.smart-sim.ru:443/api/" . $phone_number . "/updates?uname=paul&upass=kam9345t&url=" . $url);
    curl_setopt($ch, CURLOPT_FAILONERROR, 1);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "");
//    curl_setopt($ch, CURLOPT_INTERFACE, "192.168.1.104");
    curl_setopt($ch, CURLOPT_INTERFACE, "88.196.96.108");

    $result = curl_exec($ch);
    $info = curl_getinfo($ch);
    curl_close($ch);


    if ($info['http_code'] != 200) {
        echo '{ "message": "Ошибка! HTTP: ' . $info['http_code'] . ' Проблемы с сервером.", "type": "st-error" }';
        exit();
    }
    //print_r($info['http_code']);
    $xml = simplexml_load_string($result);

    //echo '<pre>';
    //print_r($xml);
    //echo '</pre>';

    if ($xml['success'] == true) {
        $manager->create($sim);
        echo '{ "message": "Создан и подписан номер ' . $_POST['create_sim_number'] . '. Ответ сервера: '.$info['http_code'].'", "type": "st-success" }';
    }

    if ($xml->attributes()->error == 1) {
        echo '{ "message": "Ошибка! ' . $xml->error . '", "type": "st-error" }';
    }
}

check($phone_number, $url, $manager, $sim);

